<?php

namespace mpend\modules\cms\models;

use Yii;
use common\models\cms\CmsArticle;
use common\models\cms\CmsArticleLike;
use common\models\cms\CmsArticleComment;

/**
 * 资讯点赞模型
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class ArticleLikeForm extends \common\base\Model {

    /**
     * @var integer 用户UID
     */
    public $user_id;

    /**
     * @var integer 资讯ID
     */
    public $article_id;

    /**
     * @var integer 评论ID
     */
    public $comment_id = 0;

    /**
     * @return array validation rules
     */
    public function rules() {
        return [
            [['user_id', 'article_id', 'comment_id'], 'integer'],
            [['article_id'], 'required'],
            [['article_id'], 'validateArticle'],
            [['comment_id'], 'validateComment'],
        ];
    }

    /**
     * 校验文章是否存在
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateArticle($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $exist = CmsArticle::find()->active(CmsArticle::STATUS_ACTIVE)->where([
            'id' => $this->$attribute,
        ])->exists();
        if (!$exist) {
            $this->addError($attribute, '资讯内容不存在');
        }
    }

    /**
     * 校验评论是否存在
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateComment($attribute) {
        $commentId = $this->$attribute;
        if ($this->hasErrors() || !$this->$attribute) {
            return;
        }
        $exist = CmsArticleComment::find()->active(CmsArticleComment::STATUS_ACTIVE)->where([
            'id' => $commentId,
        ])->exists();
        if (!$exist) {
            $this->addError($attribute, '回复内容不存在');
        }
    }

    /**
     * 保存动态点赞信息
     * @return boolean
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('点赞操作参数校验失败');
        }
        $model = CmsArticleLike::findOrNew($this->attributes);
        if (!$model->isNewRecord) {
            return !$model->delete();
        }
        return $model->save();
    }

}
